package main

import (
	portainer "portainer_manager/src"
	"strings"
	"time"

	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
)

func main() {
	for _, v := range GLOBAL_RESTART_CONTAINERS {
		go func(c *containerConfig) {
			for { // 7*24
				err := restartContainer(c, true)
				if err != nil {
					logrus.Error(err, c)
					sendMsg("提醒", err.Error())
					break
				}
				time.Sleep(1 * time.Minute)
			}
		}(v)
	}
	for _, v := range GLOBAL_STOP_CONTAINERS {
		go func(c *containerConfig) {
			for { // 7*24
				err := restartContainer(c, false) // stop
				if err != nil {
					logrus.Error(err, c)
					sendMsg("提醒", err.Error())
					break
				}
				time.Sleep(1 * time.Minute)
			}
		}(v)
	}
	select {}
}

func restartContainer(cfg *containerConfig, restart bool) error {
	now := time.Now()
	restartTime, _ := time.ParseInLocation("20060102 15:04", time.Now().Format("20060102")+" "+cfg.ExecTime[0:5], time.Local) // 下次重启时间
	if now.After(restartTime) {                                                                                               // 过时,加1天
		restartTime = restartTime.AddDate(0, 0, 1)
	}
	if restart {
		logrus.Infof("%s 上的 %s 将在 %s 重启", cfg.EndPoint, cfg.ContainerName, restartTime.Format("2006/01/02 15:04:05"))
	} else {
		logrus.Infof("%s 上的 %s 将在 %s 停止", cfg.EndPoint, cfg.ContainerName, restartTime.Format("2006/01/02 15:04:05"))
	}
	time.Sleep(time.Until(restartTime))
	var err error
	p := portainer.NewPortainer(GLOBAL_CONFIG)
	logrus.Info("auth ...")
	err = p.Auth()
	if err != nil {
		return errors.Wrap(err, "auth")
	}
	// logrus.Println(p.Token)
	var endPoint portainer.Endpoint
	eps, _ := p.ListEndpoints()
	for _, e := range eps {
		if strings.HasPrefix(e.Name, cfg.EndPoint) {
			endPoint = e
			goto FIND_ENDPOINT
		}
	}
	return errors.New("未找到对应的 EndPoint")
FIND_ENDPOINT:
	// bs, _ := json.Marshal(endPoint)
	// logrus.Println(string(bs))
	cs, _ := p.ListContainers(endPoint.Id)

	var container portainer.Container
	for _, c := range cs {
		for _, v := range c.Names {
			if v == "/"+cfg.ContainerName {
				container = c
				goto FIND
			}
		}
	}
	return errors.New("未找到 Container")
FIND:
	// 停止
	if container.State == "running" { // 运行 -> 停开
		logrus.Infof("stop %s %s", endPoint.Name, container.Names[0])
		_, err = p.StopContainer(endPoint.Id, container.ID)
		if err != nil {
			return errors.Wrap(err, "stop container")
		}
	}

	// 开
	if restart {
		logrus.Infof("start %s %s", endPoint.Name, container.Names[0])
		_, err = p.StartContainer(endPoint.Id, container.ID)
		if err != nil {
			return errors.Wrap(err, "start container")
		}
	}
	return nil
}
